package com.bky.config;

import com.bky.redis.RedisService;
import com.bky.util.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author shipeilei
 * @Date Created on 2018/5/3
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{
    public static int CACHE_TIMEOUT = 180;
    @Autowired
    private RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie cookie = CookieUtils.getCookieFromCookies(request.getCookies(), "sso.jd.com");
        if (null == cookie){
            response.sendRedirect("/toLogin.do");
            return true;
        }
        String userId = cookie.getValue();
        if (!redisService.exists(userId)){
            LoginContext.remove();
            response.sendRedirect("/toLogin.do");
            return true;
        }
        redisService.expire(userId, LoginInterceptor.CACHE_TIMEOUT);
        return true;
    }
}
